<template>
    <div class="surface-container">
        <div class="left-container">
            <el-card class="card-body">
                <!-- <div slot="header"><span>模型设置</span></div> -->
                <div class="surface-message">
                    <div class="borad-class">
                        <div class="box-class" style="height: 25%;">
                            <div>物料:
                                <div class="real-font" v-if="radarRealData!=undefined&&radarRealData!=null">{{radarRealData.siloMaterial}}</div>
                            </div>
                        </div> 
                        <div class="box-class" style="height: 25%;">
                            <div>密度:
                                <div class="real-font" v-if="radarRealData!=undefined&&radarRealData!=null">{{Number(radarRealData.siloDensity).toFixed(2)}}t/m³</div>
                            </div>
                        </div> 
                        <div class="box-class" style="height:25%">
                            <div>设备状态:
                                <div class="real-font" v-if="radarRealData!=undefined&&radarRealData!=null">{{radarRealData.isOnline==1?"在线":"离线"}}</div>
                            </div>
                        </div>  
                        <div class="box-class" style="height:25%">
                            <div>运行状态:
                                <div class="real-font" v-if="calStatus!=undefined&&calStatus!=null">{{calStatus}}</div>
                            </div>
                        </div>  
                    </div>
                    <div class="borad-class">
                        <div class="box-class">
                            <div>体积:
                                <div class="real-font" v-if="radarRealData!=undefined&&radarRealData!=null">{{Number(radarRealData.linerVol).toFixed(2)}}m³</div>
                            </div>
                        </div> 
                        <div class="box-class">
                            <div>重量:
                                <div class="real-font" v-if="radarRealData!=undefined&&radarRealData!=null">{{Number(radarRealData.linerWeigh).toFixed(2)}}t</div>
                            </div>
                        </div> 
                        <div class="box-class">
                            <div>容比:
                                <div class="real-font" v-if="radarRealData!=undefined&&radarRealData!=null">{{Number(radarRealData.perLevel).toFixed(2)}}%</div>
                            </div>
                        </div> 
                    </div>
                    <div class="borad-class">
                        <div class="box-class">
                            <div>最高:
                                <div class="real-font" v-if="radarRealData!=undefined&&radarRealData!=null">{{Number(radarRealData.linerMax).toFixed(2)}}m</div>
                            </div>
                        </div> 
                        <div class="box-class" >
                            <div>最低:
                                <div class="real-font" v-if="radarRealData!=undefined&&radarRealData!=null">{{Number(radarRealData.linerMin).toFixed(2)}}m</div>
                            </div>
                        </div> 
                        <div class="box-class">
                            <div>平均:
                                <div class="real-font" v-if="radarRealData!=undefined&&radarRealData!=null">{{Number(radarRealData.linerLev).toFixed(2)}}m</div>
                            </div>
                        </div> 
                    </div>
                </div>
                <div class="split-message">
                    <div class="borad-class" style="width: 50%;">
                        <div class="box-class" style="height:50%;">
                            <el-form size="small" :inline="true" label-width="90px">
                                <el-form-item label="区域选择">
                                    <el-select class="select-class" v-model="splitData.splitId" placeholder="请选择" clearable filterable @change="initSplit()">
                                        <el-option
                                            v-for="item in siloSplitList"
                                            :key="item.splitId"
                                            :label="item.splitName"
                                            :value="item.splitId">
                                            <span>{{item.splitName}}</span>
                                            <span class="el-icon-close" @click.stop="removeOption(item)"></span>
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-form>
                        </div>
                        <div class="box-class" style="height:50%;align-items: flex-start;">
                            <el-button
                                type="danger"
                                plain
                                size="mini"
                                @click="clearSplit()"
                            >清空</el-button>
                        </div>
                    </div>
                    <div class="borad-class" style="width: 25%;">
                        <div class="box-class" style="height:50%;">
                            <div>体积:
                                <div class="real-font" v-if="splitData.splitVol!=undefined&&splitData.splitVol!=null">{{Number(splitData.splitVol).toFixed(2)}}m³</div>
                            </div>
                        </div> 
                        <div class="box-class" style="height:50%">
                            <div>重量:
                                <div class="real-font" v-if="splitData.splitWeight!=undefined&&splitData.splitWeight!=null">{{Number(splitData.splitWeight).toFixed(2)}}t</div>
                            </div>
                        </div>  
                    </div>
                    <div class="borad-class" style="width: 25%;">
                        <div class="box-class">
                            <div>最高:
                                <div class="real-font" v-if="splitData.splitMax!=undefined&&splitData.splitMax!=null">{{Number(splitData.splitMax).toFixed(2)}}m</div>
                            </div>
                        </div> 
                        <div class="box-class" >
                            <div>最低:
                                <div class="real-font" v-if="splitData.splitMin!=undefined&&splitData.splitMin!=null">{{Number(splitData.splitMin).toFixed(2)}}m</div>
                            </div>
                        </div> 
                        <div class="box-class">
                            <div>平均:
                                <div class="real-font" v-if="splitData.splitLev!=undefined&&splitData.splitLev!=null">{{Number(splitData.splitLev).toFixed(2)}}m</div>
                            </div>
                        </div> 
                    </div>
                </div>
            </el-card>
        </div>
        <div ref="surfaceChart" class="surface-chart"></div>
        <div ref="planeChart" class="plane-chart"></div>
        <el-dialog title="分区名称添加" :visible.sync="saveSplitOpen" width="600px" append-to-body>
            <el-form ref="splitName" :rules="rules" label-width="80px">
                <el-row>
                    <el-col>
                        <el-form-item label="分区名称" prop="splitName">
                        <el-input v-model="splitData.splitName" placeholder="请输入分区名称" maxlength="20" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitSplit">保 存</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>

import * as echarts from "echarts";
import 'echarts-gl';

// import request from '@/utils/request'
import allModel from '@/views/radarSilo/initModel/allModel';
import initModelMethod from '@/views/radarSilo/initModel/initModelMethod';
import {selectSiloList} from '@/api/radar/radarSilo';
import {getRealData} from "@/api/radar/radarReal"; 
import {selectSiloSplitList,addSiloSplit,delSplit} from '@/api/radar/radarSplit';

export default {

    data(){
        return{
            series:[],
            legend:[],
            maxMins:undefined,
            realMaxMins:undefined,
            option:undefined,
            surfaceChart:undefined, 
            planeChart:undefined,           
            surfaceIndex:undefined,   //当前曲面数组下标
            graphic:undefined,        //chart划线
            siloSplitList:[],         //分区数据
            radarRealData:undefined,
            splitData:{
                stockId:undefined,
                splitName:undefined,
                splitStart:undefined,
                splitEnd:undefined,
                splitMin:undefined,
                splitMax:undefined,
                splitLev:undefined,
                splitVol:undefined,
                splitWeight:undefined,
                isOnline:undefined,
            },
            calStatus:"计算中...",
            splitId:undefined,
            saveSplitOpen:false,
            rect:undefined,  //矩形方块
            rules: {
                splitName: [
                    { required: true, message: "模型名称不能为空", trigger: "blur" },
                    { min: 0, max: 20, message: '设备名称长度必须介于 0 和 20 之间', trigger: 'blur' }
                ],
            }
        }
    },
    mounted(){
        var param = window.location.search.split("=");
        this.splitData.stockId = param[1];
        if(!this.splitData.stockId) return this.$modal.msgError("料仓id未传递");
        this.initData();
        window.onresize = () => {
            return (() => {
                this.chartResize()
            })()
        }
    },
    beforeDestroy(){
        if(this.surfaceChart){
            this.surfaceChart.dispose();
            this.surfaceChart = null;
        } 
    },
    methods:{
        initData(){
            selectSiloList({type:'1',siloStockId:this.splitData.stockId}).then(res=>{
                this.siloWithConf = res.data.data[0]
                if(!this.siloWithConf) return this.$modal.msgError("该料仓未建立");
                this.initSiloModel();
            });
            this.getSplitData();
        },
        realMethods(){
            // this.initSurface(); //获取曲面数据
            this.getRealData();  //获取实时数据
        },
        getRealData(){
            getRealData({stockId:this.splitData.stockId}).then(res=>{
                this.radarRealData = res.data[0];
                this.initSurface();
            });
        },
        getSplitData(){
            selectSiloSplitList({type:'1',stockId:this.splitData.stockId}).then(res=>{
                this.siloSplitList = res.data.data
            });
        },
        initSiloModel(){
            var siloConf = this.siloWithConf
            var object = initModelMethod.initConfModel(siloConf);
            // this.maxMins = object.realMaxMins;
            this.realMaxMins = object.realMaxMins;
            this.series = object.series;
            this.legend = object.legend;
            //这里添加一个interval,实时数据和实时曲面同时获取
            this.realMethods();
            // this.realInterval = setInterval(()=>{
            //     this.calStatus="计算完成";
            //     this.realMethods();
                
            //     setTimeout(()=>{
            //         this.calStatus="计算中...";
            //     },3000)
            // },20000)
            this.initPlaneChart();
        },

        initSurface(){
            // getSurface({stockId:this.splitData.stockId}).then(res=>{
            // })
            var surfaceData = JSON.parse(this.radarRealData.siloSurface)

            
            if(this.surfaceChart){
                this.editMax();
                this.series[this.surfaceIndex].data = surfaceData;
                this.option.visualMap[1].min = this.radarRealData.linerMin;
                this.option.visualMap[1].max = this.radarRealData.linerMax;
                this.option.series = this.series;
                this.option.title.text = this.siloWithConf.siloStockName
            }else{
                this.legend.push('曲面');
                this.series.push({
                    name:'曲面',
                    type: 'surface',
                    data: surfaceData,
                    wireframe: {
                    show: false
                    },
                    // silent: true,
                })
                this.surfaceIndex = this.series.length - 1;

                this.option = {
                    title:{
                        text:this.siloWithConf.siloStockName,
                        left: 'center',
                    },
                    tooltip: {
                        show:true,
                    },
                    legend:{
                        // right:'1%',
                        top:'30',
                        data:this.legend
                    },
                    animation: false,
                    visualMap:[ {
                    show: false,
                    inRange: {
                        color: [
                        'rgba(0,0,0,0.2)'
                        ]
                    }
                    },{
                        seriesIndex:this.surfaceIndex,
                        show: false,
                        min: this.radarRealData.linerMin,
                        max: this.radarRealData.linerMax,
                        inRange: {
                            color: [
                                'rgb(0,0,205)',
                                'rgb(72,209,204)',
                                'rgb(0,255,127)',
                                'rgb(255,255,0)',
                                'rgb(255,0,0)'
                            ]
                        }
                    }],
                    xAxis3D: {
                        // axisPointer: { show: false }
                        min:this.realMaxMins[0],
                        max:this.realMaxMins[1],
                    },
                    yAxis3D: {
                        // axisPointer: { show: false }
                        min:this.realMaxMins[2],
                        max:this.realMaxMins[3],
                    },
                    zAxis3D: {
                        // axisPointer: { show: false }
                    },
                    grid3D: {},
                    series: this.series,
                };
                this.surfaceChart = echarts.init(this.$refs.surfaceChart);
            }
            this.surfaceChart.setOption(this.option,true);
        }, 
        editMax(){
            this.option.xAxis3D.min = this.realMaxMins[0];
            this.option.xAxis3D.max = this.realMaxMins[1];
            this.option.yAxis3D.min = this.realMaxMins[2];
            this.option.yAxis3D.max = this.realMaxMins[3];
        },
        initPlaneChart(){
            var minX = this.realMaxMins[0];
            var maxX = this.realMaxMins[1];
            var minY = this.realMaxMins[2];
            var maxY = this.realMaxMins[3];

            // var step = 0.01;
            // var countX = (maxX - minX)*100;
            // var countY = (maxY - minY)*100;
            // for(var i = 1; i <= countX ;i++) dataX.push(this.maxMins[0]+=step)
            // for(var i = 1; i <= countY ;i++) dataY.push(this.maxMins[0]+=step)
            var option = {
                title:{
                    text:  "分割映射",
                    left: 'center',
                },
                tooltip:{
                    show:true,
                    trigger:'axis',
                    axisPointer: {
                        type: 'cross',
                        lineStyle: {
                            type: 'dashed', // 设置为虚线
                        }
                    }
                },
                xAxis: {
                    name:"X",
                    type: 'value',
                    min: minX, // 设置Y轴最小值
                    max: maxX,
                    // interval:maxX-minX,
                    axisLine: {
                     show:true,
                    },
                    splitLine:{
                        show:false,
                        // interval:'1',
                        // showMaxLine:true,
                    }
                },
                yAxis: {
                    name:"Y",
                    show: true,
                    type: 'value',
                    min: minY, // 设置Y轴最小值
                    max: maxY,
                    // interval:maxY-minY,
                    axisLine: {
                        show:true,
                    },
                    splitLine:{
                        show:false,
                        // interval:'1',
                        // showMaxLine:true,
                    }
                },
                grid:{
                    show:false,
                },
                graphic:this.graphic,
                series: [
                    {
                        type:"line",
                    }
                ]
            };
            this.planeChart = echarts.init(this.$refs.planeChart);
            this.planeChart.setOption(option,true);
            this.initMirrorBot();
            this.moveMouseChart();
        },
        initMirrorBot(){
            var minPixel = this.planeChart.convertToPixel({seriesIndex: 0}, [this.realMaxMins[0],this.realMaxMins[2]]);
            var maxPixel = this.planeChart.convertToPixel({seriesIndex: 0}, [this.realMaxMins[1],this.realMaxMins[3]]);
            // console.log(minPixel,maxPixel)
            this.graphic = [];
            this.graphic.push({
                type: 'rect',
                shape: {
                    x: Math.min(minPixel[0],maxPixel[0]),
                    y: Math.min(minPixel[1],maxPixel[1]),
                    // z: 0, // 设置z轴为0，保持在XY平面上
                    width: Math.abs(maxPixel[0]-minPixel[0]),
                    height: Math.abs(maxPixel[1]-minPixel[1])
                },
                style: {
                    fill: 'rgba(255,255,255,0)',
                    stroke: 'rgba(0,0,0,1)',
                    lineWidth: 1
                }
            });
            this.planeChart.setOption({
                graphic: this.graphic
            });
        },
        moveMouseChart(){
            let startX, startY, endX, endY;
            let coordStartX, coordStartY, coordEndX, coordEndY;
            let minX,maxX,minY,maxY;
            var that = this;
            this.planeChart.getZr().on('mousedown', function (params) {
                // 坐标转化
                const coord = that.planeChart.convertFromPixel({seriesIndex: 0}, [params.offsetX, params.offsetY]);
                var pixel = that.pixelBorder(coord);
                startX = pixel[0];
                startY = pixel[1];
                coordStartX = coord[0]
                coordStartY = coord[1]
                    // 如果已经有矩形存在，则先移除它
                    if (that.rect) {
                        that.series.splice(-4,4);
                        that.graphic.splice(-1,1);
                        that.planeChart.setOption({
                            graphic: that.graphic
                        });
                        that.rect = undefined;
                        that.surfaceChart.setOption({series:that.series})
                    }
                    
                // }

            });

            this.planeChart.getZr().on('mousemove', function (params) {
                if (startX !== undefined && startY !== undefined) {
                    // 再次进行坐标转换
                    const coord = that.planeChart.convertFromPixel({seriesIndex: 0}, [params.offsetX, params.offsetY]);

                    var pixel = that.pixelBorder(coord);
                    endX = pixel[0];
                    endY = pixel[1];
                    coordEndX = coord[0]
                    coordEndY = coord[1]
                    // [minX,maxX,minY,maxY]
                    var minMaxArray = that.formSplitSquare(startX,startY,endX,endY,coordStartX,coordStartY,coordEndX,coordEndY,that);
                    minX = minMaxArray[0];
                    maxX = minMaxArray[1];
                    minY = minMaxArray[2];
                    maxY = minMaxArray[3];

                }
            });

            this.planeChart.getZr().on('mouseup', function () {
                if(that.surfaceChart){
                    // 在这里可以执行其他逻辑，比如保存矩形信息等
                    var surfaceData = that.series[that.surfaceIndex].data
                    let sum = 0,num = 0;
                    let min,max,lev;
                    // console.log(",,",surfaceData)
                    surfaceData.forEach(item => {
                        if((item[0] > minX && item[0] <maxX) && (item[1] > minY && item[1] < maxY)){
                            sum += item[2];
                            num++;
                            min = min > item[2]?min:item[2]
                            max = max < item[2]?max:item[2]
                        }
                    });
                    lev = (sum/num).toFixed(2);
                    min = (min).toFixed(2);
                    max = (max).toFixed(2);
                                        //         x: Math.min(coordStartX, coordEndX),
                        //         y: Math.min(coordStartY, coordEndY),
                    var squareLong = Math.abs(coordStartX-coordEndX);
                    var squareWidth = Math.abs(coordStartY-coordEndY);
                    var square = squareLong*squareWidth*lev

                    that.splitData.splitStart = startX+","+startY;
                    that.splitData.splitEnd = endX+","+endY;
                    that.splitData.splitMin = min;
                    that.splitData.splitMax = max;
                    that.splitData.splitLev = lev;
                    that.splitData.splitVol = square;
                    that.splitData.splitWeight = square*that.siloWithConf.siloDensity;

                    that.saveSplitOpen = true;
                }

                startX = startY = endX = endY = undefined; // 重置起点坐标
            });
        },
        formSplitSquare(startX,startY,endX,endY,coordStartX,coordStartY,coordEndX,coordEndY,that){

            const width = endX - startX;
            const height = endY - startY;
            if (that.rect) {
                that.series.splice(-4,4);
                that.graphic.splice(-1,1);
            }
            that.rect = {
                type: 'rect',
                shape: {
                    x: Math.min(startX, endX),
                    y: Math.min(startY, endY),
                    // z: 0, // 设置z轴为0，保持在XY平面上
                    width: Math.abs(width),
                    height: Math.abs(height)
                },
                style: {
                    fill: 'rgba(0,179,255,0.3)',
                    stroke: '#00B3FF',
                    lineWidth: 2
                }
            };
            that.graphic.push(that.rect)
            that.planeChart.setOption({
                graphic: that.graphic
            });

            var squareLong = Math.abs(coordStartX-coordEndX);
            var squareWidth = Math.abs(coordStartY-coordEndY);
            var minX = coordStartX<coordEndX?coordStartX:coordEndX;
            var maxX = coordStartX>coordEndX?coordStartX:coordEndX;
            var minY = coordStartY<coordEndY?coordStartY:coordEndY;
            var maxY = coordStartY>coordEndY?coordStartY:coordEndY;
            var squareHeight = Number(that.siloWithConf.siloHeight);
            
            if(!that.surfaceChart) return;

            var startXSeries = allModel.planeHorModel([squareLong,squareLong,squareHeight
            ,squareHeight,0,0,0,0,minX + that.realMaxMins[0],minY + that.realMaxMins[2],0]).series;

            var endXSeries = allModel.planeHorModel([squareLong,squareLong,squareHeight
            ,squareHeight,0,0,0,0,minX + that.realMaxMins[0],maxY + that.realMaxMins[2],0]).series;

            var startYSeries = allModel.planeLonModel([squareWidth,squareWidth,squareHeight
            ,squareHeight,0,0,0,0,minX + that.realMaxMins[0],minY + that.realMaxMins[2],0]).series;

            var endYSeries = allModel.planeLonModel([squareWidth,squareWidth,squareHeight
            ,squareHeight,0,0,0,0,maxX + that.realMaxMins[0],minY + that.realMaxMins[2],0]).series;

            that.series.push(startXSeries);
            that.series.push(endXSeries);
            that.series.push(startYSeries);
            that.series.push(endYSeries);
            that.surfaceChart.setOption({series:that.series})
            return [minX,maxX,minY,maxY];
        },
        initSplit(){
            if(!this.splitData.splitId){
                this.splitData.splitId = undefined;
                this.clearSplit();
            }else{
                var splitIndex = this.siloSplitList.findIndex((item) => item.splitId == this.splitData.splitId);
                this.splitData = JSON.parse(JSON.stringify(this.siloSplitList[splitIndex]));
                var splitStart = this.splitData.splitStart.split(",");
                var splitEnd = this.splitData.splitEnd.split(",");
                const coordStart = this.planeChart.convertFromPixel({seriesIndex: 0}, splitStart);
                const coordEnd = this.planeChart.convertFromPixel({seriesIndex: 0}, splitEnd);
                this.formSplitSquare(splitStart[0],splitStart[1],splitEnd[0],splitEnd[1],coordStart[0],coordStart[1],coordEnd[0],coordEnd[1],this);
            }

        },
        clearSplit(){
            if (this.rect) {
                this.reset();
                this.series.splice(-4,4);
                this.graphic.splice(-1,1);
                this.initPlaneChart();
                this.rect = undefined;
                if(this.surfaceChart)this.surfaceChart.setOption(this.option,true)
            } 
        },
        reset() {
            this.splitData = {
                stockId:undefined,
                splitName:undefined,
                splitStart:undefined,
                splitEnd:undefined,
                splitMin:undefined,
                splitMax:undefined,
                splitLev:undefined,
                splitVol:undefined,
                splitWeight:undefined,
                isOnline:undefined,
            };
        },
        submitSplit(){
            if(!this.splitData.splitName) return this.$message.error("区域名称不能为空");
            addSiloSplit(this.splitData).then(res=>{
                this.$modal.msgSuccess("添加成功");
                this.getSplitData();
            })
            this.saveSplitOpen = false;
        },
        removeOption(siloSplit){
            this.$modal.confirm('是否确认删除名称为"' + siloSplit.splitName + '"的数据项？').then(function() {
                return delSplit(siloSplit.splitId);
            }).then(() => {
                this.splitData.splitId = undefined;
                this.getSplitData();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
        },
        pixelBorder(coord){
            if(coord[0] < this.realMaxMins[0]){
                coord[0] = this.realMaxMins[0]
            }else if(coord[0] > this.realMaxMins[1]){
                coord[0] = this.realMaxMins[1]
            }

            if(coord[1] < this.realMaxMins[2]){
                coord[1] = this.realMaxMins[2]
            }else if(coord[1] > this.realMaxMins[3]){
                coord[1] = this.realMaxMins[3]
            }
            var pixel = this.planeChart.convertToPixel({seriesIndex: 0}, coord);
            return pixel;
        },
        chartResize(){
            if(this.surfaceChart) {
                this.surfaceChart.resize()
            }
            if(this.planeChart) {
                this.planeChart.resize()
                this.initMirrorBot();
            }
        },
        cancel(){
            this.saveSplitOpen = false;
        }

    }

}
</script>

<style lang="scss" scoped>
    .surface-container{
        width: 100%;
        height: 100%;
        background-color: rgba(5, 251, 255, 0.2);
    }
    .left-container{
        position: absolute;
        top: 1%;
        left: 2%;
        width: 96%;
        height: 20%;
    }
    .card-body{
        width: 100%;
        height: 100%;
        background-color: rgba(230, 255, 255, 1);
    }
    ::v-deep .el-card__body {
        padding: 20px 20px 20px 20px;
        width: 100%;
        height: 100%;
    }
    ::v-deep .el-dialog__body {
        padding: 20px 20px 0px;
    }
    .dialog-footer{
        text-align: center;
    }
    .el-icon-close{
        float: right;
        line-height: 34px;
        font-weight: bold;
    }
    .el-icon-close:hover{
        color: 	#4169E1;
    }

    .borad-class{
        float: left;
        width: 33.3%;
        height: 100%;
    }
    .box-class{
        float: left;
        width: 100%;
        height: 33.3%;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .select-class{
        float: left;
        width: 150px;
    }
    .real-font{
        color: red;
        display: inline-block;
    }

    .surface-chart{
        position: absolute;
        left: 2%;
        width:45%;
        bottom: 5%;
        height: 70%;
    }
    .plane-chart{
        position: absolute;
        right: 2%;
        width:45%;
        bottom: 5%;
        height: 70%;
    }
    .surface-message{
        float:left;
        width: calc(48% - 20px);
        height: 100%;
    }
    .split-message{
        float: right;
        width: calc(48% - 20px);
        height: 100%;
    }

</style>